//============================================================================
// Name        : memory_mapping.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
#include<error.h>
#include <cstdlib>
#include <iostream>
#include<string.h>
#include<fstream>
#include<vector>
#include <algorithm>
#define FILEPATH "/home/kriwtal/workspace/memory_mapping/src/file1.txt"
#define FILEPATHout "/home/kriwtal/workspace/memory_mapping/src/testout.txt"

using namespace std;

int main() {
	int fdIn,fdOut;
	char *ptr;
	fdIn=open(FILEPATH, O_RDWR, S_IRWXO);
	if(fdIn==-1)
	{
		cout<<"Error opening the file!: "<<strerror(errno)<<endl;
		exit(1);
	}
	cout<<"fdIn"<<fdIn<<endl;
	struct stat buf;
	stat(FILEPATH, &buf);
	cout << "Size of file to be mapped=" << buf.st_size << endl;
	int Size_of_File=buf.st_blksize;
	cout<<"Block size"<<Size_of_File<<endl;
	ptr = (char*) mmap(NULL, buf.st_blksize, PROT_WRITE | PROT_READ, MAP_SHARED,fdIn, 0);
	if (ptr == MAP_FAILED) {
			cout << "Mapping failed! :"<<strerror(errno) << endl;
			exit(2);
		}
	close(fdIn);
	fdOut=open(FILEPATHout,O_CREAT |O_RDWR,S_IRWXO);
	if(fdOut==-1)
		{
			cout<<"Error opening the file!: "<<strerror(errno)<<endl;
			exit(1);
		}
	cout<<"fdOut"<<fdOut<<endl;
	vector<int> Vector_of_numbers;
	string Veryfier=" 0123456789";
	string Numbers="0123456789";
	int Num = 0;
	int Size=buf.st_size/sizeof(char);
	//ptr++;
	int i=0;
	while(*ptr!=NULL){
		if(Veryfier.find_first_of(*ptr,0 )==-1){
			cout<<"Verifier"<<Veryfier.find(*ptr,0 )<<endl;
			cout<<"File is incompatible with format!"<<"Try again!"<<endl;
			break;
		}
	cout<<  "Position of char is"<<	Veryfier.find_first_of(*ptr,0)<<endl;
	if(Veryfier.find_first_of(*ptr,0)!=0){
		Num=Num * 10 + ((unsigned int) (*ptr - '0'));
			i++;
	}
	if(Veryfier.find_first_of(*ptr,0)==0){
		if(i>0)
			{
			Vector_of_numbers.push_back(Num);
			cout<<"Number written= "<<Num<<endl;
			Num=0;
			i=0;
			}
		else{
			cout<<"We founr one more __!"<<endl;
		}
	}
	ptr++;
	if(Veryfier.find_first_of(ptr,0)==-1){
		if(i>0){
			Vector_of_numbers.push_back(Num);
			cout<<"Last Num is "<<Num<<endl;
		}
	}
}
	sort(Vector_of_numbers.begin(),Vector_of_numbers.end());
	vector<int>::iterator j =Vector_of_numbers.begin();
	while(j!=Vector_of_numbers.end()){
		cout<<"Number = "<<*j<<endl;
		j++;
	}
	int Bytes_written;
	Bytes_written=write( fdOut, ptr, Size_of_File);
	cout<<"Bytes Written "<<Bytes_written<<endl;
	cin.get();
	close(fdOut);

	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	return 0;
}
